var API = {
     base: 'https://api.soojl.com/',
    // base: 'http://192.168.1.108/',
    // base: 'http://172.16.10.13:8083/',
    // base: 'http://172.16.50.85:8022/',
    user: {
        login: 'api/user/login',
        sessionKey: 'https://api.weixin.qq.com/sns/jscode2session',
        normal: 'api/user/normal',
        coach: 'api/user/coach',
        attributes: 'api/user/coach/attributes',
        types: 'api/user/coach/types',
        edit: 'api/user/edit',
        coachAdd: 'api/user/coach/add',
        coachEdit: 'api/user/coach/edit',
        setLocation: 'api/user/location/set',
        activityorders: 'api/user/activityorders',
        learn: 'api/usre/learn',
        teaching: 'api/user/teaching',
        students: 'api/user/students',
        coachorders: 'api/user/coachorders',
        feedback_add: 'api/user/feedback/add',
        nearby:'api/nearby/coachs',
        payorder:'api/user/payorder',
        cards:'api/user/cards',
        bankEdit:'api/user/bank/edit',
        balance:'api/user/balance'
    },
    coach: {
        list: 'api/coach/list',
        detail: 'api/coach/detail',
        evaluates: 'api/coach/evaluates',
        evaluates_add: 'api/coach/evaluate/add',
        types: 'api/coach/types'
    },
    order: {
        coachAdd: 'api/order/coach/add',
        activity_add: 'api/order/activity/add'
    },
    file: {
        uploadImage: 'api/upload/image'
    },
    recommend: {
        activities: 'api/home/recommend/activities',
        articles: 'api/home/recommend/articles'
    },
    activity: {
        activities: 'api/activity/activities',
        detail: 'api/activity/detail',
        book: 'api/order/activity/add',
        advertisements: 'api/home/recommend/advertisements'
    },
    search: {
        search: 'api/search'
    },
    pay: {
        wechat: {
            prepay: 'api/pay/wechat/prepay'
        },
        notify: 'api/pay/notify'
    },
    article: {
        articles: 'api/article/list',
        detail: 'api/article/detail',
        comments: 'api/article/comments',
        comment_add: 'api/article/comment/add'
    }
},
    app = {
        id: 'wx28ac69a1a813e375',
        secret: 'b6f5b2012034707ca1aa54f6dd3ea13f',
    },
    application = null,
    userInfo = wx.getStorageSync('userInfo'),
    header = {
        deviceId: "",
        deviceName: "",
        osName: "",
        osVersion: "",
        versionName: "",
        versionCode: "6",
        token: "",
        cmd: "",
        source: 1
    }, _ = {
        /**
         * @param {string} type
         * @param {string} url
         * @param {object} params
         * @param {Function} [callback]
         * @param {Function} [fallback]
         * @param {Function} [error]
         */
        ajax: function (type, async, url, params, callback, fallback, error) {
            let authorization = '';
            if (userInfo) {
                authorization = userInfo.id + '|' + userInfo.token;
                header.token = userInfo.openId;
            }
            params && (params['header'] = header);
            wx.request({
                method: type,
                url: API.base + url,
                data: JSON.stringify(params),
                async: async,
                dataType: 'json',
                header: { 'content-type': 'application/json; charset=UTF-8', 'Authorization': authorization },
                success: function (res) {
                    var data = (res && res['data']) || {};
                    if (data['header']) {
                        var msg = data['header']['statusMsg'],
                            code = data['header']['statusCode'];
                        if (code == 1000) {
                            //msg && layer.msg(msg); FIXME
                            typeof callback == "function" && callback(data);
                        } else if (code == 9997) {
                            application || (application = getApp());
                            application.getUserInfo(function (info) {
                                userInfo = info;
                                _.ajax(type, async, url, params, callback, fallback, error);
                            });
                        } else if (code == 10019) {
                            wx.showToast({
                                title: msg,
                                duration: 3000
                            });
                            wx.setStorage({
                                key: 'userInfo',
                                data: null,
                            });
                            application || (application = getApp());
                            application.getUserInfo(function (info) {
                                userInfo = info;
                                _.ajax(type, async, url, params, callback, fallback, error);
                            });
                            /* wx.redirectTo({
                                url: 'pages/account/booking/booking'
                            });*/
                        } else {
                            // layer.msg(msg);
                            typeof fallback == "function" && fallback(data);
                        }
                    }
                },
                fail: function (err) {
                    wx.showToast({
                        title: err.errMsg,
                        icon: 'success',
                        duration: 2000
                    });
                    typeof error == "function" && error(err);
                }
            });
        },
        /**
         * @param {string} url
         * @param {object} params
         * @param {Function} [callback]
         * @param {Function} [fallback]
         * @param {Function} [error]
         */
        post: function (url, params, callback, fallback, error) {
            _.ajax('post', false, url, params || {}, callback, fallback, error);
        },
        /**
         * @param {string} url
         * @param {object} params
         * @param {Function} [callback]
         * @param {Function} [fallback]
         * @param {Function} [error]
         */
        asynPost: function (url, params, callback, fallback, error) {
            _.ajax('post', true, url, params || {}, callback, fallback, error);
        },
        /**
         * @param {string} url
         * @param {object} [params]
         * @param {Function} [callback]
         * @param {Function} [fallback]
         * @param {Function} [error]
         */
        asynGet: function (url, params, callback, fallback, error) {
            _.ajax('get', true, url, params || {}, callback, fallback, error);
        },
        /**
         * @param {string} url
         * @param {object} [params]
         * @param {Function} [callback]
         * @param {Function} [fallback]
         * @param {Function} [error]
         */
        get: function (url, params, callback, fallback, error) {
            _.ajax('get', false, url, params || {}, callback, fallback, error);
        },
        /**
         * Upload a file to the specified location
         * @param domain
         * @param store
         * @param filePath
         */
        uploadFile: function (domain, store, filePath, callback, fallback, error) {
            var params = {
                'store': store,
                'header': JSON.stringify(header)
            };
            wx.uploadFile({
                url: domain,
                filePath: filePath,
                formData: params,
                name: 'files',
                success: function (res) {
                    var data = (res && JSON.parse(res['data'])) || {};
                    if (data['header']) {
                        var code = data['header']['statusCode'];
                        if (code == 1000) {
                            typeof callback == "function" && callback(data);
                        } else {
                            typeof fallback == "function" && fallback(data);
                        }
                    }
                },
                fail: function (err) {
                    typeof error === "function" && error(err);
                }
            });
        },
        /**
         * Template format tools.
         * usage:
         * 1).template('I can find {0}!, your id is: {1}-{1}-{2}-{3}', 'Chiroc', 22322, 4353, 'IIUTYG')
         *  output: I can find Chiroc!, your id is: 22322-22322-4353-IIUTYG
         * 2).template('I can find your {name}, {age}, {title.main}, {title.mains}, {title.sub-title.tip}', {name: 'Chiroc', age: 24, title: {main: 0, 'sub-title': {tip: 'YUI'}}})
         *  output: I can find your Chiroc, 24, 0, {title.mains}, YUI
         * @param {string} text The value's indicators, can be HTML or plain text with {0}, {1}, {name}, or {object.name} format.
         * @param {string | object} settings Indicators value.
         * @returns {XML|string|void}
         */
        template: function (text, settings) {
            var interpolate = /\{(.*?)\}/g,
                isObj = typeof settings === 'object',
                format = function () {
                    var s = '', size = arguments[0].length, i = 1;
                    s = arguments[0][0];
                    for (; i < size; i++) {
                        s = s.split('{' + (i - 1) + '}').join(arguments[0][i]);
                    }
                    return s;
                },
                getValue = function (namespace, match, settings) {
                    var keys = namespace.split('.'),
                        _getValue = function (keys, settings) {
                            for (var i = 0, size = keys.length; i < size; i++) {
                                var key = keys[i];
                                if (typeof settings[key] !== 'object') {
                                    return settings[key];
                                } else {
                                    settings = settings[key];
                                }
                            }
                            return match;
                        }, result = _getValue(keys, settings);

                    return (result === undefined ? match : result);
                };

            if (arguments.length < 2) {
                return text;
            }

            if (!isObj) {
                return format(arguments);
            }

            return arguments.length == 2 && isObj && text.replace(interpolate, function (match, escape, interpolate, evaluate, offset) {
                return escape.split('.').length < 2 ? (isObj ? (settings[escape] == undefined ? '' : settings[escape]) : settings) : getValue(escape, match, settings);
            });
        },
        /**
         * Format date object to string
         *
         * @param {Date|number} dt
         * @param {String} [fmt] e.g.: 'yyyy-MM-dd hh:mm:ss'
         * @return {String}
         */
        formatDate: function (dt, fmt) {
            var o = {
                "M+": dt.getMonth() + 1, //月份 
                "d+": dt.getDate(), //日 
                "h+": dt.getHours(), //小时 
                "m+": dt.getMinutes(), //分 
                "s+": dt.getSeconds(), //秒 
                "q+": Math.floor((dt.getMonth() + 3) / 3), //季度 
                "S": dt.getMilliseconds() //毫秒 
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (dt.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        setUserInfo: function (value) {
            wx.setStorage({
                key: 'userInfo',
                data: value,
            });
            userInfo = value;
        }
    }
module.exports = {
    API: API,
    app: app,
    post: _.post,
    get: _.get,
    asynPost: _.asynPost,
    asynGet: _.asynGet,
    template: _.template,
    formatDate: _.formatDate,
    uploadFile: _.uploadFile,
    setUserinfo: _.setUserInfo,
}
